package com.xiaogang.ggfw.config.filter;

import com.xiaogang.ggfw.utils.sign.SignUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName : caldav
 * @作者 : 侯小刚
 * @描述 :
 * @创建日期 : 2023/4/10 11:05
 */
@Component
public class SignInterceptor implements HandlerInterceptor {

    /**
     * 特殊情况下，可以根据请求前缀忽略某些请求的验证。
     */
    private List<String> checkUrlPrefix = new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        // 如果需要校验签名
        if (isCheckPrefix(uri)) {
            // 校验签名
            return SignUtils.checkSign(httpServletRequest,httpServletResponse);
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * 某些特别url需要校验签名
     * @param uriPrefix
     * @return
     */
    public SignInterceptor addCheckUrls(String uriPrefix) {
        if(!checkUrlPrefix.contains(uriPrefix)) {
            checkUrlPrefix.add(uriPrefix);
        }
        return this;
    }

    /**
     * 校验是不是需要校验签名的url
     * @param uri
     * @return
     */
    private boolean isCheckPrefix(String uri) {
        boolean isCheckPrefix = false;
        for (String p : checkUrlPrefix) {
            if (uri.startsWith(p)) {
                isCheckPrefix = true;
                break;
            }
        }
        return isCheckPrefix;
    }

}
